#coding: utf-8
import sys, json, time, base64, datetime, random
sys.path.append("/code/base")
import redis
import pymysql
from base import config

class PageDb:
    def __init__(self, app='debug', appid=None, pagein=None):
        self.app = app

        self.config = config.get_app_config(app=self.app)

        self.dbs = [
            self.s_rdb(0), # 系统 - 配置数据库
            self.s_rdb(1),
            self.s_rdb(2),
            self.s_rdb(3)
        ]

    def rdb(self, host, password, dbidx=0):
        pool = redis.ConnectionPool(host=host, db=dbidx, password=password)
        return redis.StrictRedis(connection_pool=pool)

    def s_rdb(self, dbidx=0):
        sys_config = config.getSysConfig()
        return self.rdb(host=sys_config['aliyun']['redis']['host'], password=sys_config['aliyun']['redis']['password'], dbidx=dbidx)

    def p_rdb(self, dbidx=0):
        return self.rdb(host=self.config['product']['aliyun']['redis']['host'], password=self.config['product']['aliyun']['redis']['password'], dbidx=dbidx)

    def mdb(self, dbname, host, user, password):
        conn = pymysql.connect(
            host = host,
            user = user,
            passwd = password
        )

        conn.select_db(dbname)
        cur = conn.cursor(pymysql.cursors.DictCursor)

        conn.set_character_set('utf8mb4')
        cur.execute('SET NAMES utf8mb4;') 
        cur.execute('SET CHARACTER SET utf8mb4;')
        cur.execute('SET character_set_connection=utf8mb4;')
        return conn, cur

    def s_mdb(self):
        return self.mdb(dbname="mycar",
                host=self.config['sys']['aliyun']['rds']['host'],
                user=self.config['sys']['aliyun']['rds']['account'],
                password=self.config['sys']['aliyun']['rds']['password'])

    def p_mdb(self):
        dbname = self.app
        return self.mdb(dbname=dbname,
                host=self.config['product']['aliyun']['rds']['host'],
                user=self.config['product']['aliyun']['rds']['account'],
                password=self.config['product']['aliyun']['rds']['password'])

    def log_pv(self, app, page):
        pass

    def get_tesla_token(self, area="cn"):
        res = json.loads( self.dbs[0].hget("TeslaToken", area).decode("utf-8") )
        return res['access_token']
